import 'dart:io';
import 'package:flutter/material.dart';
import 'package:mobx/mobx.dart';
import 'package:hinge/common/index.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';
import 'package:uuid/uuid.dart';
import 'package:path_provider/path_provider.dart';

part 'release_store.g.dart';

class ReleaseStore = _ReleaseStore with _$ReleaseStore;

abstract class _ReleaseStore with Store {
  // 香水图片
  @observable
  File? perfumeImage;

  // 香水标题
  @observable
  String title = '';

  // 香水描述
  @observable
  String description = '';

  // 香水分类（Strong fragrance, Eau de Toilette, Woody）
  @observable
  String category = 'Strong fragrance';

  // 是否推荐
  @observable
  bool isRecommend = true;

  // 是否正在提交
  @observable
  bool isSubmitting = false;

  // 是否显示错误提示
  @observable
  bool showErrors = false;

  // 选择图片
  @action
  Future<void> selectImage(BuildContext context) async {
    final List<AssetEntity>? result = await AssetPicker.pickAssets(
      context,
      pickerConfig: AssetPickerConfig(
        maxAssets: 1,
        requestType: RequestType.image,
      ),
    );

    if (result != null && result.isNotEmpty) {
      final File? file = await result.first.file;
      if (file != null) {
        perfumeImage = file;
      }
    }
  }

  // 设置标题
  @action
  void setTitle(String value) {
    title = value;
  }

  // 设置描述
  @action
  void setDescription(String value) {
    description = value;
  }

  // 设置分类
  @action
  void setCategory(String value) {
    category = value;
  }

  // 设置是否推荐
  @action
  void setIsRecommend(bool value) {
    isRecommend = value;
  }

  // 重置表单
  @action
  void reset() {
    perfumeImage = null;
    title = '';
    description = '';
    category = 'Strong fragrance';
    isRecommend = true;
    showErrors = false;
  }

  // 验证表单
  @computed
  bool get isValid {
    return perfumeImage != null && title.isNotEmpty && description.isNotEmpty;
  }

  // 提交表单
  @action
  Future<bool> submit() async {
    // 显示验证错误
    showErrors = true;

    if (!isValid) {
      return false;
    }

    isSubmitting = true;

    try {
      // 获取当前登录用户
      final currentUser = UserService.getCurrentUser();
      if (currentUser == null) {
        isSubmitting = false;
        return false;
      }

      // 获取所有香水，找到最大ID
      final perfumes = PerfumeService.getAllPerfumes();
      final maxId =
          perfumes.isEmpty
              ? 0
              : perfumes.map((e) => e.id).reduce((a, b) => a > b ? a : b);

      // 创建新香水
      final String imagePath =
          "assets/images/perfume_${const Uuid().v4().substring(0, 8)}.png";
      // 将图片保存到本地文件系统
      final String savedImagePath = await _saveImageToLocal(
        perfumeImage!,
        imagePath,
      );

      // 创建香水模型
      final perfume = PerfumeModel(
        id: maxId + 1,
        category: category,
        userId: currentUser.id,
        title: title,
        description: description,
        isRecommend: isRecommend,
        isVideo: false,
        url: savedImagePath,
        favoriteCount: 0,
        likeCount: 0,
        commentCount: 0,
      );

      // 保存香水信息
      await PerfumeService.addPerfume(perfume);

      isSubmitting = false;
      return true;
    } catch (e) {
      print('发布香水失败: $e');
      isSubmitting = false;
      return false;
    }
  }

  // 保存图片到本地文件系统
  Future<String> _saveImageToLocal(File imageFile, String targetPath) async {
    final directory = await getApplicationDocumentsDirectory();
    final String fileName = targetPath.split('/').last;
    final String filePath = '${directory.path}/$fileName';
    await imageFile.copy(filePath);
    return filePath;
  }
}
